package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.XiaoMeiYiRongParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class XiaoMeiYiRongReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        String apiKey = sourceBaseInfo.getApiKey();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String companyId = jsonObjectParamContent.getString("companyId");
        if (!apiKey.equals(companyId)){
            sourceApiResult.setReturnObject(this.getError("公司ID不符合"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(data);
        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("phoneMd5")) ||
                jsonObject.getInteger("age") == null ||
                jsonObject.getInteger("loanAmount") == null ||
                StrUtil.isEmpty(jsonObject.getString("mapCode")) ||
                StrUtil.isEmpty(jsonObject.getString("cityName")) ||
                StrUtil.isEmpty(jsonObject.getString("extName")) ||
                StrUtil.isEmpty(jsonObject.getString("creditCardLimit")) ||
                StrUtil.isEmpty(jsonObject.getString("accumulationFund")) ||
                StrUtil.isEmpty(jsonObject.getString("socialSecurity")) ||
                StrUtil.isEmpty(jsonObject.getString("sesameSeeds")) ||
                StrUtil.isEmpty(jsonObject.getString("existRoom")) ||
                StrUtil.isEmpty(jsonObject.getString("vehicleCondition")) ||
                StrUtil.isEmpty(jsonObject.getString("commercialInsurance")) ||
                StrUtil.isEmpty(jsonObject.getString("occupation")) ||
                StrUtil.isEmpty(jsonObject.getString("lengthOfMaturity")) ||
                StrUtil.isEmpty(jsonObject.getString("requestId")) ||
                jsonObject.getInteger("advertId") == null){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);


        // 获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddresInfoByCity(userDataParam.getCity());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());



        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        String apiKey = sourceBaseInfo.getApiKey();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String companyId = jsonObjectParamContent.getString("companyId");
        if (!apiKey.equals(companyId)){
            sourceApiResult.setReturnObject(this.getError("公司ID不符合"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(data);

        XiaoMeiYiRongParam xiaoMeiYiRongParam = JSON.parseObject(paramContentData, XiaoMeiYiRongParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(xiaoMeiYiRongParam.getPhone());
        userDataParam.setRealName(xiaoMeiYiRongParam.getCustomerName());

        String requestId = xiaoMeiYiRongParam.getRequestId();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), requestId);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "操作成功！");
        JSONObject dataObject = new JSONObject();
        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){
            // 下游是 非 apis 类型
            dataObject.put("companyName", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", companyLogo);
            }

            dataObject.put("productName", thirdBaseInfo.getProductName());
            dataObject.put("price", pushResultInfo.getPriceAmount());
        }else {
            dataObject.put("companyName", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
            }
            dataObject.put("productName", merchantBaseInfo.getInfoName());
            dataObject.put("price", pushResultInfo.getPriceAmount());
        }


        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 500);
        returnObject.put("msg", message);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "推送成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        XiaoMeiYiRongParam xiaoMeiYiRongParam = JSON.parseObject(paramContent, XiaoMeiYiRongParam.class);

        UserDataParam userDataParam = new UserDataParam();

        userDataParam.setOutOrderNo(xiaoMeiYiRongParam.getRequestId());

        userDataParam.setMobileMd5(xiaoMeiYiRongParam.getPhoneMd5());
        userDataParam.setMobile(xiaoMeiYiRongParam.getPhone());
        userDataParam.setRealName(xiaoMeiYiRongParam.getCustomerName());

        if (StringUtils.isEmpty(xiaoMeiYiRongParam.getSex())){
            userDataParam.setSex("0");
        }else if ("0".equals(xiaoMeiYiRongParam.getSex())){
            userDataParam.setSex("1");
        }else {
            userDataParam.setSex("2");
        }

        userDataParam.setAge(xiaoMeiYiRongParam.getAge());

        userDataParam.setCity(xiaoMeiYiRongParam.getExtName());

        userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());

        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());

        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());

        if (StringUtils.isEmpty(xiaoMeiYiRongParam.getMonthlyIncome())){
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        }else if ("1".equals(xiaoMeiYiRongParam.getMonthlyIncome()) || "-2".equals(xiaoMeiYiRongParam.getMonthlyIncome())){
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        }else if ("2".equals(xiaoMeiYiRongParam.getMonthlyIncome())){
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr002.getValue());
        }else {
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr004.getValue());
        }

        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());

        userDataParam.setUserIp("127.0.0.1");

        Integer loanAmount = xiaoMeiYiRongParam.getLoanAmount();
        if (loanAmount == null){
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        }else {
            if (loanAmount <= 30000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
            } else if (loanAmount > 30000 && loanAmount <= 50000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
            } else if (loanAmount > 50000 && loanAmount <= 100000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
            } else if (loanAmount >100000 && loanAmount <= 200000) {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
            } else {
                userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
            }

        }


        String houseProperty = xiaoMeiYiRongParam.getExistRoom();
        if ("-2".equals(houseProperty)){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else if ("1".equals(houseProperty)){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu004.getValue());
        }

        String commercialInsurance = xiaoMeiYiRongParam.getCommercialInsurance();
        if ("-2".equals(commercialInsurance)){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
        }

        String creditCardLimit = xiaoMeiYiRongParam.getCreditCardLimit();
        if ("1".equals(creditCardLimit) || "2".equals(creditCardLimit)){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else {
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq004.getValue());
        }

        String hasFund = xiaoMeiYiRongParam.getAccumulationFund();
        if ("-2".equals(hasFund)){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else if ("2".equals(hasFund)){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }

        String zhimaCredit = xiaoMeiYiRongParam.getSesameSeeds();
        if ("4".equals(zhimaCredit)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else if ("3".equals(zhimaCredit)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if ("2".equals(zhimaCredit)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else if ("1".equals(zhimaCredit)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }else {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
        }

        String hasSocial = xiaoMeiYiRongParam.getSocialSecurity();
        if ("-2".equals(hasSocial)){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else if ("2".equals(hasSocial)){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
        }else {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }

        String carProperty = xiaoMeiYiRongParam.getVehicleCondition();
        if ("-2".equals(carProperty)){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else if ("1".equals(carProperty)){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car003.getValue());
        }

        String professional = xiaoMeiYiRongParam.getOccupation();
        if ("1".equals(professional) || "2".equals(professional)){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if ("6".equals(professional)){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if ("8".equals(professional)){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }if ("3".equals(professional) || "4".equals(professional) || "7".equals(professional)){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
        }else{
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
        }

        String loanTerm = xiaoMeiYiRongParam.getLengthOfMaturity();
        if (Integer.valueOf("3") == Integer.valueOf(loanTerm) || Integer.valueOf("4") == Integer.valueOf(loanTerm)){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt004.getValue());
        }else if (Integer.valueOf("2") == Integer.valueOf(loanTerm)){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt003.getValue());
        }else {
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());
        }


        return userDataParam;
    }

}
